package com.qf.hospital.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.system.entity.Report;
import com.qf.hospital.system.enums.HospitalEnum;
import com.qf.hospital.system.exception.HospitalEx;
import com.qf.hospital.system.mapper.ReportMapper;
import com.qf.hospital.system.service.ReportService;
import com.qf.hospital.system.vo.ReportVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Override
    @Transactional
    public void deleteBeforeReportUser() {
        reportMapper.deleteByTimeAndState();
    }

    @Override
    public List<ReportVO> findByCCAndCondition(Integer cc, String value) {
        //1. 查询数据
        List<ReportVO> list = reportMapper.findByCCAndCondition(cc, value);

        //2. 将身份证号隐藏一波
        for (ReportVO reportVO : list) {
            String carid = reportVO.getCarid();
            reportVO.setCarid(carid.substring(0,6) + "****" + carid.substring(14));
        }
        //3. 返回
        return list;
    }

    @Override
    public boolean findCountByPhone(String phone) {
        return reportMapper.findCountByPhoneOrCarid("phone",phone) > 0;
    }

    @Override
    public boolean findCountByCarid(String carid) {
        return reportMapper.findCountByPhoneOrCarid("carid",carid) > 0;
    }


    @Override
    @Transactional
    public void addReport(Report report) {
        //1. 封装数据
        report.setTime(new Date());
        report.setState(1);

        //2. 保存
        int count = reportMapper.insertSelective(report);

        //3. 判断
        if(count != 1){
            log.error("【添加挂号信息】 添加挂号信息失败！！ report = {}",report);
            throw new HospitalEx(HospitalEnum.ADD_REPORT_ERROR);
        }
    }

    @Override
    public PageInfo<ReportVO> findByConditionAndPage(Integer page,Integer limit,String name) {
        //1. 分页
        PageHelper.startPage(page,limit);
        //2. 查询(本类方法)
        List<ReportVO> list = this.findByCCAndCondition(2, name);
        //3. 封装
        PageInfo<ReportVO> pageInfo = new PageInfo<>(list);
        //4. 返回
        return pageInfo;
    }

    @Override
    public String findPathogenyByReportId(Integer reportId) {
        return reportMapper.findPathogenyByReportId(reportId);
    }

    @Override
    public void updatePatientPathogenyByReportId(String bing, Integer reportId) {
        Integer count = reportMapper.updatePatientPathogenyByReportId(bing, reportId);

        if(count != 1){
            log.error("【修改病因】 修改病因失败！！ bing = {}，reportId = {}",bing,reportId);
            throw new HospitalEx(HospitalEnum.UPDATE_BING_ERROR);
        }
    }


}
